<?php

namespace app\common\model;

use think\Model;


class Distributionregion extends Model
{





    // 表名
    protected $name = 'distribution_region';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'jsonconfig'
    ];


    protected static function init()
    {
        self::beforeInsert(function ($row) {
            $changed = $row->getChangedData();
            if (isset($changed['province_id'])) {
                $row->province = db('cnarea')->where('area_code', $changed['province_id'])->value('name');
            }
            if (isset($changed['city_id'])) {
                $row->city = db('cnarea')->where('area_code', $changed['city_id'])->value('name');
            }
            if (isset($changed['area_id'])) {
                $row->area = db('cnarea')->where('area_code', $changed['area_id'])->value('name');
            }
            $row->address = $row->province . $row->city . $row->area;
        });
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            if (isset($changed['province_id'])) {
                $row->province = db('cnarea')->where('area_code', $changed['province_id'])->value('name');
            }
            if (isset($changed['city_id'])) {
                $row->city = db('cnarea')->where('area_code', $changed['city_id'])->value('name');
            }
            if (isset($changed['area_id'])) {
                $row->area = db('cnarea')->where('area_code', $changed['area_id'])->value('name');
            }
        });
    }


    public function getJsonconfigAttr($v, $d)
    {
        $list = Distributionconfig::where('pid', $d['id'])->select();
        if ($list) {
            return json_encode($list);
        } else {
            return '';
        }
    }




    public function distribution()
    {
        return $this->belongsTo('app\common\model\Distribution', 'pid', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
